package service

import (
	"user-center/dto"
	"user-center/entity"
	"user-center/query"
	"user-center/vo"

	"github.com/androidsr/sc-go/model"
	"github.com/androidsr/sc-go/sbuilder"
	"github.com/androidsr/sc-go/sc"
	"github.com/androidsr/sc-go/sgorm"
)

type SysRolesService struct {
}

func NewSysRolesService() SysRolesService {
	service := SysRolesService{}
	return service
}

// 使用id获取数据
func (m SysRolesService) Get(id string) vo.SysRolesVO {
	data := new(entity.SysRoles)
	data.Id = id
	err := sgorm.DB.GetOne(data)
	if err != nil {
		return vo.SysRolesVO{}
	}
	return sc.Copy[vo.SysRolesVO](data)
}

// 保存数据
func (m SysRolesService) Save(dto *dto.SysRolesDTO) error {
	data := sc.Copy[entity.SysRoles](dto)
	err := sgorm.DB.Insert(data)
	return err
}

// 更新数据
func (m SysRolesService) UpdateById(dto *dto.SysRolesDTO) error {
	dbEntity := new(entity.SysRoles)
	sgorm.DB.GetOne(dbEntity)
	sc.CopyTo(dto, dbEntity)
	err := sgorm.DB.UpdateById(dbEntity).Error
	return err
}

// 删除数据
func (m SysRolesService) DeleteById(id string) error {
        err := sgorm.DB.DeleteById(entity.SysRoles{}, id)
	return err
}

// 分页列表查询
func (m SysRolesService) QueryPage(query *query.SysRolesQueryDTO) *model.PageResult {
	sql := `select * from sys_roles a `
	data := make([]entity.SysRoles, 0)
	b := sbuilder.StructToBuilder(query, sql)
	sql, values := b.Build()
	return sgorm.DB.SelectPage(&data, query.BaseQueryDTO.Page, sql, values...)
}

// 分页下拉查询
func (m SysRolesService) QueryList(query *model.SelectQueryDTO) *model.PageResult {
	sql := `select a.id as value, a.role_name as label from sys_roles a where 1=1 `
	data := make([]model.SelectVO, 0)
	b := sbuilder.Builder(sql)
	b.Like("CONCAT(a.id,a.role_name)", query.Label)
	for k, v := range query.Vars {
		b.Eq(k, v)
	}
	b.Multiple().Ors(b.In("a.id", query.Selected))
	sql, values := b.Build()
	return sgorm.DB.SelectPage(&data, &query.Page, sql, values...)
}
